package org.example.leetCode;

/**
 * @author Administrator
 */
public class connect {
    public Node connect(Node root) {
        root.next = null;
        if (root.left == null) {
            return root;
        }
        return link(root);
    }

    public Node link(Node node) {
        node.left.next = node.right;
        node.right.next = null;
        if (node.left.left != null) {
            node.left.right.next = node.right.left;
        }
        if (node.left != null) {
            node.left = link(node.left);
            node.right = link(node.right);
        }
        return node;
    }

    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }

    ;
}
